package com.example.sys.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.config.ResponseBean;
import com.example.config.UnicomResponseEnums;
import com.example.sys.entity.RoleMenu;
import com.example.sys.entity.User;
import com.example.sys.entity.UserRole;
import com.example.sys.service.RoleMenuService;
import com.example.sys.service.RoleService;
import com.example.sys.service.UserRoleService;
import com.example.sys.service.UserService;
import com.example.sys.vo.UserSelectVo;
import com.example.util.NetworkUtil;
import com.example.util.UserRegisteAndLogin;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author anan
 * @since 2019-06-13
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    //    新增
    @PostMapping("/add")
    @RequiresPermissions({"system:user:add"})
    public ResponseBean<UnicomResponseEnums> register(@Valid User user, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
//       客户端IP地址
        String str = NetworkUtil.getIP(request);
        if (user.getUserName() != null) {
//            用户名
            String loginName = user.getUserName();
//            密码
            String password = user.getPassword();
//            盐值、密文
            String[] strs = UserRegisteAndLogin.encryptPassword(loginName, password);
            user.setSalt(strs[1]);
            user.setPassword(strs[0]);
//            登陆IP
            if (str != null) user.setLoginIp(str);
            user.setLoginDate(LocalDateTime.now());
//          向数据库写入
            userService.save(user);
            return new ResponseBean(true, user, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true, UnicomResponseEnums.REGISTER_ERROR);
    }

    //    删除
    @DeleteMapping("/deleteUserById")
    @RequiresPermissions({"system:user:remove"})
    public ResponseBean<UnicomResponseEnums> deleteUserById(@RequestBody @Valid User user) {
        if (user.getUserId() == 1) {
            return new ResponseBean(true, UnicomResponseEnums.ADMINISTRATOR_USER_NOT_DELETE);
        }
        Boolean count = userService.removeById(user.getUserId());
        if (!count)
            return new ResponseBean(false, UnicomResponseEnums.OPERATION_FAILED);
        return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
    }

    //    批量删除
    @DeleteMapping("/deleteUserByIds")
    @RequiresPermissions({"system:user:remove"})
    public ResponseBean<UnicomResponseEnums> deleteUserByIds(List<Long> userIds) {
        if (!userIds.isEmpty()) {
            for (Long userId : userIds) {
                userService.removeById(userId);
            }
            return new ResponseBean(false, UnicomResponseEnums.OPERATION_FAILED);
        }
        return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
    }

    //    更新
    @RequestMapping("/updateUser")
    @RequiresPermissions({"system:user:edit"})
    public ResponseBean<UnicomResponseEnums> updateUser(@Valid User user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", user.getUserId());
        user.setUserId(null);
//        Boolean count = userService.updateById(user, updateWrapper);
        Boolean count = userService.update(user, updateWrapper);
        if (count) {
            return new ResponseBean(true, null, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(false, UnicomResponseEnums.OPERATION_FAILED);

    }

    //    批量更新更新
    @RequestMapping("/updateUsers")
    @RequiresPermissions({"system:user:edit"})
    public ResponseBean<UnicomResponseEnums> updateUsers(@Valid List<User> users) {
        if (!users.isEmpty()) {
            for (User user : users) {
                updateUser(user);
            }
            return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(false, UnicomResponseEnums.OPERATION_FAILED);
    }

    //    获取全部用户
    @RequestMapping("/getUserList")
    @RequiresPermissions({"system:user:list"})
    public ResponseBean<UnicomResponseEnums> getUserList(UserSelectVo userSelectVo) {
        System.out.println(userSelectVo);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userSelectVo, false, true);
        System.out.println(stringObjectMap);
        if (stringObjectMap.isEmpty()) {
            System.out.println("空查询");
            List<User> list = userService.list();
            return new ResponseBean(true, list, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true, userService.selectPage(userSelectVo), UnicomResponseEnums.SUCCESS_OPTION);
    }

    @RequestMapping("/getUser")
    @RequiresPermissions({"system:user:list"})
    public ResponseBean<UnicomResponseEnums> getUser(Long userId) {
        if (!userId.toString().isEmpty()) {
            User user = userService.getById(userId);
            return new ResponseBean(true, user, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(false, UnicomResponseEnums.OPERATION_FAILED);
    }

    @GetMapping("/getUserByDeptId")
    @RequiresPermissions({"system:user:list"})
    public ResponseBean<UnicomResponseEnums> getUserByDeptId(Long deptId) {
        List<User> list = new ArrayList<>();
        String str = "%" + deptId + "%";
        list = userService.getUserByDeptId(str);
        return new ResponseBean(true, list, UnicomResponseEnums.SUCCESS_OPTION);
    }

    @GetMapping("/getUserByDeptIds")
    @RequiresPermissions({"system:user:list"})
    public ResponseBean<UnicomResponseEnums> getUserByDeptIds(String deptIds) {
        List<User> list = new ArrayList<>();
        list = userService.getUserByDeptIds(deptIds);
        return new ResponseBean(true, list, UnicomResponseEnums.SUCCESS_OPTION);
    }

    @PostMapping("/updateUserByUserId")
    @RequiresPermissions({"system:user:list"})
    public ResponseBean<UnicomResponseEnums> updateUserByUserId(@RequestBody @Valid User user) {
        if (user.getUserId()==1)return new ResponseBean(true, UnicomResponseEnums.ADMIN_ROLE_NOT_UPDATE);
        Boolean bool = userService.updateById(user);
        if (bool) {
            return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
        }
        return new ResponseBean(true, UnicomResponseEnums.OPERATION_FAILED);
    }

    /**
     * 根据前台传回来的token，获取用户的信息
     * @param token
     * @return
     */
    @GetMapping("/info")
    public ResponseBean<UnicomResponseEnums> info(String token){

        System.out.println(token);
//      获取userId
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("token", token);
        Long userId=userService.getOne(wrapper).getUserId();
//      获取用户权限
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("user_id", userId);
        List<UserRole> userRoles= userRoleService.list(wrapper1);
//        List<Long> list = new ArrayList<>();
//        for (UserRole userRole : userRoles) {
//            list.add(userRole.getRoleId());
//        }
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.in("role_id",list);
//        queryWrapper.groupBy("menu_id");
//        List<RoleMenu> listMenu=roleMenuService.list(queryWrapper);
//        List<Long> list1 = new ArrayList<>();
//        for (RoleMenu roleMenu : listMenu) {
//            list1.add(roleMenu.getMenuId());
//        }
        
//      获取用户的权限数组
        List<String> list1 = new ArrayList<>();
        for (UserRole userRole: userRoles) {
            list1.add(roleService.getById(userRole.getRoleId()).getRoleKey());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("roles",list1);
        map.put("introduction", "I am a super administrator");
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name", "Super Admin");

        return new ResponseBean(true,map, UnicomResponseEnums.SUCCESS_OPTION);
    }

}
